import { IProxy } from '@/typing';
import { concatMap, Observable, of, Subject, map, tap, defer, catchError, forkJoin, from } from 'rxjs';
import BaseSourceFetcher from '@/modules/proxy/proxy-source/base-source-fetcher';
import IHelper from '@/services/helper.service';
import axios from 'axios';
import ILogger from '@/services/logger.service';

export default class ProxySource04 extends BaseSourceFetcher {
  updater$: Subject<IProxy>
  fetch(updater$: Subject<IProxy>) {
    this.updater$ = updater$
    console.log(`ProxySource04 fetch`)
    from(axios.get(`http://proxylist.fatezero.org/proxy.list`)).pipe(
      map(res => this.parseContent(res.data)),
      catchError(error => {
        ILogger.error(`Proxy source 4 fetch failed. error: ${error.message}`)
        return of(null)
      })
    ).subscribe()
  }

  debug() {
    from(axios.get(`http://proxylist.fatezero.org/proxy.list`)).pipe(
      map(res => this.parseContent(res.data)),
      catchError(error => {
        ILogger.error(`Proxy source 4 fetch failed. error: ${error.message}`)
        return of(null)
      })
    ).subscribe()
  }

  parseContent(content: string) {
    let reg = /\{(.+?)}/g
    let matched = content.match(reg)
    matched.forEach(line => this.parseLine(line))
  }
  parseLine(line: string): IProxy | undefined {
    let proxy: IProxy | undefined = undefined
    try {
      let lineProxy = JSON.parse(line)
      proxy = {
        host: lineProxy.host,
        port: lineProxy.port,
        last_time: IHelper.timeFormatted(),
        region: "",
        source: "source-04"
      }
      this.updater$.next(proxy)
    } catch (e) {}
    return proxy
  }
}